package com.ruix.app.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;

import com.ruix.app.widget.comment.SpannableStringBuilderCompat;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hadexs on 2017/5/22.
 */

public class PostsTagsContentView extends TextView{


    //用户名颜色
    private int textColor = 0xFF307E9E;

    public PostsTagsContentView(Context context) {
        super(context);
//        setMovementMethod(MyLinkMovementMethod.getInstance());
    }

    public PostsTagsContentView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
//        setMovementMethod(MyLinkMovementMethod.getInstance());
    }

    public PostsTagsContentView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
//        setMovementMethod(MyLinkMovementMethod.getInstance());
    }

    public void setContentText(String contentText) {
        if (!TextUtils.isEmpty(contentText)){
            setSpannableString(contentText);
        }
    }


//    private void setSpannableString(String contentText) {
//        SpannableString ss = new SpannableString(contentText);
//        String regex = "[a-zA-z]+://[^\\s]*";
//        Pattern pattern = Pattern.compile(regex);
//        Matcher matcher = pattern.matcher(contentText);
//        ArrayList<String> urls = new ArrayList();
//        ArrayList<Integer> start = new ArrayList();
//        ArrayList<Integer> end = new ArrayList();
//        // 字符串是否与正则表达式相匹配
//        while (matcher.find()) {
//            urls.add(matcher.group());
//            start.add(matcher.start());
//            end.add(matcher.end());
//        }
//        for (int i = 0; i < urls.size(); i++) {
//            ss.setSpan(new MyClickableSpan(urls.get(i)), start.get(i), end.get(i),
//                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
//        }
//        setText(ss);
//    }


    private void setSpannableString(String contentText) {
        SpannableString ss = new SpannableString(contentText);
        String regEx = "#([^#]+?)#";//="#[^#]+#";  // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(contentText);
        ArrayList<Integer> start = new ArrayList();
        ArrayList<Integer> end = new ArrayList();
        // 字符串是否与正则表达式相匹配
        while (matcher.find()) {
            start.add(matcher.start());
            end.add(matcher.end());
        }
        for (int i = 0; i < start.size(); i++) {
            ss.setSpan(new ForegroundColorSpan(textColor), start.get(i), end.get(i),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        setText(ss);
    }


}
